<template>
    <el-card>
        <!-- 标题 -->
        <div class="title">
            <h2>{{ isEdit ? '编辑医生' : '新增医生' }}</h2>
        </div>

        <!-- 表单 -->
        <el-form :model="doctorForm" label-width="110px" size="default">
            <el-row :gutter="20">
                <!-- 第一行 -->
                <el-col :span="8">
                    <el-form-item label="医生编号">
                        <el-input v-model="doctorForm.doctorId" :disabled="true" />
                    </el-form-item>
                </el-col>
                <el-col :span="8">
                    <el-form-item label="账号" required>
                        <el-input v-model="doctorForm.phone" placeholder="请输入手机号或邮箱" />
                    </el-form-item>
                </el-col>
                <el-col :span="8">
                    <el-form-item label="医生头像">
                        <div style="display: flex; align-items: center; gap: 10px;">
                            <el-avatar :size="40" :src="doctorForm.avatar" />
                            <el-button type="primary" link>+点击上传</el-button>
                        </div>
                    </el-form-item>
                </el-col>
            </el-row>

            <el-row :gutter="20">
                <!-- 第二行 -->
                <el-col :span="8">
                    <el-form-item label="医生姓名" required>
                        <el-input v-model="doctorForm.name" placeholder="请输入" />
                    </el-form-item>
                </el-col>
                <el-col :span="8">
                    <el-form-item label="医生角色" required>
                        <el-select v-model="doctorForm.roleId" placeholder="请选择" style="width: 100%">
                            <el-option label="请选择" value="" />
                            <el-option v-for="item in roleList" :key="item._id" :label="item.name" :value="item._id" />
                        </el-select>
                    </el-form-item>
                </el-col>
                <el-col :span="8">
                    <el-form-item label="登录密码">
                        <el-input v-model="doctorForm.password" type="password" placeholder="请输入" />
                    </el-form-item>
                </el-col>
            </el-row>

            <el-row :gutter="20">
                <!-- 第三行 -->
                <el-col :span="8">
                    <el-form-item label="性别">
                        <el-select v-model="doctorForm.gender" placeholder="请选择" style="width: 100%">
                            <el-option label="请选择" value="" />
                            <el-option label="男" value="1" />
                            <el-option label="女" value="0" />
                        </el-select>
                    </el-form-item>
                </el-col>
                <el-col :span="8">
                    <el-form-item label="医生所属机构" required>
                        <el-select v-model="doctorForm.organizationId" placeholder="请选择" style="width: 100%">
                            <el-option label="请选择" value="" />
                            <el-option v-for="item in organizationList" :key="item._id" :label="item.name"
                                :value="item._id" />
                        </el-select>
                    </el-form-item>
                </el-col>
            </el-row>

            <el-row :gutter="20">
                <!-- 第三行 - 医生简介 -->
                <el-col :span="24">
                    <el-form-item label="医生简介">
                        <el-input v-model="doctorForm.intro" type="textarea" :rows="4" placeholder="请输入医生简介"
                            style="width: 100%" />
                    </el-form-item>
                </el-col>
            </el-row>

            <el-row :gutter="20">
                <!-- 第四行 - 医生擅长 -->
                <el-col :span="24">
                    <el-form-item label="医生擅长">
                        <el-input v-model="doctorForm.skill" type="textarea" :rows="4" placeholder="请输入医生擅长领域"
                            style="width: 100%" />
                    </el-form-item>
                </el-col>
            </el-row>

            <!-- 操作按钮 -->
            <el-row>
                <el-col :span="24">
                    <el-form-item>
                        <el-button type="primary" @click="handleSave">保存</el-button>
                        <el-button @click="handleReturn">返回</el-button>
                    </el-form-item>
                </el-col>
            </el-row>
        </el-form>
    </el-card>
</template>

<script setup lang="ts">
import { onMounted, ref, computed } from 'vue'
import { ElMessage } from 'element-plus'
import { addDoctorsApi, updateDoctorsApi, findOrganizationsApi, findRoleApi, getDoctorsDetailApi } from '@/api/doctors'

// 定义 props
const props = defineProps<{
    doctorId?: string  // 如果有 doctorId 则为编辑模式
}>()

// 定义事件
const emit = defineEmits(['success', 'cancel'])

// 是否为编辑模式
const isEdit = computed(() => !!props.doctorId)

onMounted(() => {
    findOrganizations()
    findRole()

    // 如果是编辑模式，加载医生数据
    if (isEdit.value) {
        loadDoctorData()
    }
})

// 获取机构列表
function findOrganizations() {
    findOrganizationsApi()
        .then(res => {
            console.log('机构API响应:', res);
            if (res.data.code == 200) {
                // 将机构数据存储到 organizationList 中
                organizationList.value = res.data.data.rows
            }
        })
}

// 获取角色
function findRole() {
    findRoleApi()
        .then(res => {
            console.log(res);
            if (res.data.code == 200) {
                roleList.value = res.data.data.rows
            }
        })
}



// 生成时间戳编号
const generateDoctorId = () => {
    const timestamp = new Date().getTime();
    return timestamp
}

// 机构数据类型定义
interface Organization {
    _id: string
    name: string
    address?: string
    contacts: string
    phone: string
    state: number
}

interface Role {
    _id: string
    name: string
    description: string
}

// 机构列表数据
const organizationList = ref<Organization[]>([])
const roleList = ref<Role[]>([])



// 表单数据 - 根据API文档调整
const doctorForm = ref({
    doctorId: generateDoctorId(), // 医生编号 (时间戳生成)
    phone: '',
    avatar: 'https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png',
    name: '',
    password: '',
    gender: '',
    intro: '',
    roleId: '',
    skill: '',
    organizationId: ''
})

// 表单验证
const validateForm = () => {
    if (!doctorForm.value.phone) {
        ElMessage.error('请输入手机号')
        return false
    }
    if (!doctorForm.value.name) {
        ElMessage.error('请输入医生姓名')
        return false
    }
    if (!doctorForm.value.password) {
        ElMessage.error('请输入登录密码')
        return false
    }
    if (!doctorForm.value.roleId) {
        ElMessage.error('请选择医生角色')
        return false
    }
    return true
}

// 保存
const handleSave = async () => {
    // 只在新增模式下进行表单验证
    if (!isEdit.value && !validateForm()) {
        return
    }

    try {
        console.log('提交数据:', doctorForm.value)
        console.log('当前模式:', isEdit.value ? '编辑' : '新增')

        let res
        if (isEdit.value) {
            // 编辑模式：调用更新接口
            const updateData = {
                ...doctorForm.value,
                _id: doctorForm.value.doctorId  // 确保包含_id字段
            }
            console.log('调用更新API:', updateData)
            res = await updateDoctorsApi(updateData)
        } else {
            // 新增模式：调用新增接口
            console.log('调用新增API:', doctorForm.value)
            res = await addDoctorsApi(doctorForm.value)
        }

        console.log('API响应:', res)

        if (res.data.code === 200) {
            ElMessage.success(isEdit.value ? '医生信息更新成功' : '医生信息保存成功')
            emit('success')
            if (!isEdit.value) {
                resetForm()
            }
        } else {
            ElMessage.error('保存失败：' + (res.data.message || '未知错误'))
        }
    } catch (error) {
        console.error('保存失败:', error)
        ElMessage.error('保存失败，请检查网络连接')
    }
}

// 获取机构ID
const getOrganizationId = (data: any) => {
    // 首先检查直接的organizationId字段
    if (data.organizationId) {
        return data.organizationId
    }

    // 如果没有直接的organizationId，从团队信息中获取
    if (data.teamIds && data.teamIds.length > 0) {
        const firstTeam = data.teamIds[0]
        if (firstTeam.organizationId) {
            // 如果是对象，返回ID
            if (typeof firstTeam.organizationId === 'object' && firstTeam.organizationId._id) {
                return firstTeam.organizationId._id
            }
            // 如果是字符串，直接返回
            if (typeof firstTeam.organizationId === 'string') {
                return firstTeam.organizationId
            }
        }
    }

    return ''
}

// 加载医生数据（编辑模式）
const loadDoctorData = async () => {
    if (!props.doctorId) return
    const res = await getDoctorsDetailApi({ _id: props.doctorId })
    console.log('加载医生数据:', res)

    if (res.data.code === 200) {
        const data = res.data.data
        doctorForm.value = {
            doctorId: data._id,
            phone: data.phone || '',
            avatar: data.avatar || 'https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png',
            name: data.name || '',
            password: data.password || '',
            gender: data.gender !== undefined ? String(data.gender) : '',
            intro: data.intro || '',
            roleId: data.roleId?._id || '',
            skill: data.skill || '',
            organizationId: getOrganizationId(data)
        }
    } else {
        ElMessage.error(res.data.message)
    }
}

// 重置表单
const resetForm = () => {
    doctorForm.value = {
        doctorId: generateDoctorId(), // 重新生成编号
        phone: '',
        avatar: 'https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png',
        name: '',
        password: '',
        gender: '',
        intro: '',
        roleId: '',
        skill: '',
        organizationId: ''
    }
}

// 返回
const handleReturn = () => {
    console.log('返回医生列表 - 等待路由实现')
    // TODO: 路由跳转回医生列表页面
}
</script>

<style scoped>
.el-card {
    width: 1150px;
    margin: 0 auto;
}

.title {
    padding-bottom: 20px;
    border-bottom: 1px solid #F2F7FB;
}

.title h2 {
    margin: 0;
    font-size: 18px;
    font-weight: 500;
    color: #333;
    position: relative;
    padding-left: 12px;
}

.title h2::before {
    content: '';
    position: absolute;
    left: 0;
    top: 50%;
    transform: translateY(-50%);
    width: 4px;
    height: 16px;
    background-color: #409EFF;
    border-radius: 2px;
}
</style>